package com.kun.springbootorder.controller;


import cn.hutool.json.JSONUtil;
import com.kun.springbootorder.entity.Order;
import com.kun.springbootorder.entity.OrderMessage;
import com.kun.springbootorder.service.impl.OrderMessageServiceImpl;
import com.kun.springbootorder.service.impl.OrderServiceImpl;
import jakarta.annotation.PostConstruct;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kunkun
 * @since 2025-02-25
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    public OrderServiceImpl orderService;

    @Autowired
    private OrderMessageServiceImpl orderMessageService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 新增订单----暴露问题
     * @param order
     * @return
     */
    @PostMapping("/insert")
    @Transactional(rollbackFor = Exception.class)
    public String insertOrder(Order order) {
        orderService.insertOrder(order);

        //调用配送服务
        String url = "http://localhost:9002/delivery/insert?orderId="+order.getOrderId() +
                "&userId="+order.getUserId()+"&orderContent="+order.getOrderContent();
        System.out.println(url);
        restTemplate.getForEntity(url,String.class);
        return "success";
    }


    /**
     * 新增订单----可靠生产
     * @param order
     * @return
     */
    @PostMapping("/insertMq")
    public String insertOrderMq(Order order) {
        //1. 保存订单（订单表和订单消息表）
        orderService.insertOrder(order);
        OrderMessage orderMessage = new OrderMessage(order.getOrderId(),order.getUserId(),order.getOrderContent(),0);
        orderMessageService.insertOrderMessage(orderMessage);
        //2. 发送消息到MQ
        String jsonMessage = JSONUtil.toJsonStr(order);
        CorrelationData correlationData = new CorrelationData(String.valueOf(order.getOrderId()));
        rabbitTemplate.convertAndSend("order_fanout_exchange","",jsonMessage,correlationData);

        return "success";
    }

    //@PostConstruct注解用于在bean初始化之后执行的方法，并且只能执行一次，非静态方法
    @PostConstruct
    public void callback(){
        //设置确认发送回执
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                Integer id = Integer.parseInt(correlationData.getId());

                if(!ack){         //消息发送失败
                    System.out.println("消息发送失败");
                    System.out.println("失败原因："+cause);
                    System.out.println("失败的消息id："+id);
                    return;
                }

                System.out.println("消息发送成功");
                System.out.println("消息id："+id);
                orderMessageService.updateStatus(id,true);

            }
        });
    }




}

